package com.wxlsoft.ui.conflist;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import java.awt.*;

/**
 * @author: 我的袜子都是洞
 */
public class ConfigTableView extends JFrame {

	FlightTableModel flight = new FlightTableModel();
	JTable table = new JTable(flight);

	ConfigTableView(String title) {
		super(title);
		init();
		setComponent();
		addComponent();
		addListener();
		setVisible(true);
	}

	private void init() {
		setSize(600, 400);
		// 设置窗口位置居中
		setLocationRelativeTo(null);
		// 设置布局
		setLayout(new BorderLayout());
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	private void setComponent() {
		// 设置第一列宽度为40
		table.getColumnModel().getColumn(0).setPreferredWidth(40);
		// 设置第二列宽度为120
		table.getColumnModel().getColumn(1).setPreferredWidth(120);

	}

	private void addComponent() {
		// 使用srcllpane会自动显示列名
		JScrollPane scrollPane = new JScrollPane(table);
		add(scrollPane, BorderLayout.CENTER);
	}

	private void addListener() {
		// selection监听器监听表格哪行被选中
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent e) {
				// 被选中的行
				int row = table.getSelectedRow();
				String str = (String) flight.getValueAt(row, 0);
				System.out.println("选中的行号是：" + row + ",航班号是：" + str);
			}
		});
	}

	public static void main(String[] args) {
		new ConfigTableView("JTable演示");
	}
}

class FlightTableModel extends AbstractTableModel {
	// 列名
	String[] columnName = new String[] { "选择", "出发时间", "飞行时间", "出发地", "目的地", "余票", "票价" };
	// 表格具体数据
	String[][] flightDate = new String[][] { { "1", "2019-01-18 10:05", "90分钟", "北京", "纽约", "50", "500.0" },
			{ "2", "2019-01-18 10:05", "90分钟", "北京", "纽约", "10", "500.0" },
			{ "3", "2019-01-18 10:05", "90分钟", "北京", "纽约", "10", "500.0" },
			{ "4", "2019-01-18 10:05", "90分钟", "北京", "纽约", "40", "500.0" }, };

	/**
	 * 返回一共多少行
	 */
	@Override
	public int getRowCount() {
		return flightDate.length;
	}

	/**
	 * 返回一共多少列
	 */
	@Override
	public int getColumnCount() {
		return columnName.length;
	}

	/**
	 * 返回每一个单元格的值
	 */
	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		return flightDate[rowIndex][columnIndex];
	}

	/**
	 * 获取每一列的名称
	 */
	@Override
	public String getColumnName(int column) {
		return columnName[column];
	}

	/**
	 * 单元格是否可以修改
	 */
	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return false;
	}
}